//
//  MZUploadImageCell.m
//  meizhuang
//
//  Created by sky on 16/8/25.
//  Copyright © 2016年 netease. All rights reserved.
//

#import <Masonry/Masonry.h>
#import "WFUploadImageCell.h"
#import <HMImagePicker/HMImagePickerController.h>
#import <HMImagePicker/HMPreviewViewController.h>

@interface MZUploadImageCollectionViewCell : UICollectionViewCell

@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) UIButton *closeButton;

@end


@implementation MZUploadImageCollectionViewCell

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        _imageView = [[UIImageView alloc] init];
        _imageView.contentMode = UIViewContentModeScaleAspectFill;
        _imageView.clipsToBounds = YES;
        [self.contentView addSubview:_imageView];
        
        [_imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.bottom.equalTo(self.imageView.superview);
        }];
        
        _closeButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_closeButton setImage:[UIImage imageNamed:@"icon_record_editor_image_delete"] forState:UIControlStateNormal];
        [self.contentView addSubview:_closeButton];
        
        [_closeButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.right.equalTo(self.closeButton.superview);
            
        }];
    }
    return self;
}

@end

@interface WFUploadImageCell()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UINavigationControllerDelegate, HMImagePickerControllerDelegate>

@end

@implementation WFUploadImageCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        _itemSize = CGSizeMake(50, 50);
        _maxCount = 5;
        _uploadPlaceholderImage = [UIImage imageNamed:@"report_img"];
        
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        flowLayout.minimumInteritemSpacing = 5;
        flowLayout.minimumLineSpacing = 5;
        flowLayout.sectionInset = UIEdgeInsetsMake(15, 15, 15, 15);
        _collectionView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:flowLayout];
        [_collectionView registerClass:[MZUploadImageCollectionViewCell class] forCellWithReuseIdentifier:@"CELL"];
        _collectionView.alwaysBounceHorizontal = YES;
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.scrollsToTop = NO;
        [self.contentView addSubview:_collectionView];
        [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.bottom.equalTo(self.collectionView.superview);
        }];
    }
    return self;
}

#pragma mark - ==================== collection delegate ================
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return MIN(self.photos.count + 1, self.maxCount);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    //加号，弹出图片选择界面
    if (indexPath.row == self.photos.count) {
        HMImagePickerController *imagePickerVC = [[HMImagePickerController alloc] initWithSelectedAssets:self.photos];
        imagePickerVC.pickerDelegate = self;
        [[UIApplication sharedApplication] sc_presentViewController:imagePickerVC
                                                           animated:YES
                                                         completion:nil];
        return;
    }
//    //查看大图
//    HMPreviewViewController *controller = [[MZImagePreviewController alloc] init];
//    controller.previewDelegate = self;
//    [[MZApplication sharedApplication] presentViewController:controller animated:YES completion:NULL];
//    controller.currentImageIndex = indexPath.row;
    
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return _itemSize;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    MZUploadImageCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CELL" forIndexPath:indexPath];
    
    if (indexPath.row == self.photos.count) {
        cell.imageView.image = self.uploadPlaceholderImage;
    }else {
        [[PHImageManager defaultManager] requestImageForAsset:self.photos[indexPath.row]
                                                   targetSize:CGSizeMake(600, 600)
                                                  contentMode:PHImageContentModeAspectFit
                                                      options:nil
                                                resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
                                                    cell.imageView.image = result;
                                                }];
    }
    cell.closeButton.hidden = (indexPath.row == self.photos.count);
    [cell.closeButton bk_removeEventHandlersForControlEvents:UIControlEventTouchUpInside];
    @weakify(self, cell);
    [cell.closeButton bk_addEventHandler:^(id sender) {
        @strongify(self, cell);
        NSIndexPath *currentIndexPath = [self.collectionView indexPathForCell:cell];
        [self removeImageAtIndexPath:currentIndexPath];
    } forControlEvents:UIControlEventTouchUpInside];
    
    return cell;
}

- (void)removeImageAtIndexPath:(NSIndexPath *)indexPath {
    BOOL needReload = self.photos.count == self.maxCount;
    NSMutableArray *arr = [NSMutableArray arrayWithArray:self.photos];
    [arr removeObjectAtIndex:indexPath.row];
    self.photos = arr;
    //4张图时会重新添加+号，使用`deleteItemsAtIndexPaths:`会因为dataSource.count没变化而crash
    if (needReload) {
        [self.collectionView performBatchUpdates:^{
            [self.collectionView reloadSections:[NSIndexSet indexSetWithIndex:0]];
        } completion:nil];
    }else {
        [self.collectionView deleteItemsAtIndexPaths:@[indexPath]];
    }
}

#pragma mark - ==================== image picker ================
- (void)imagePickerController:(HMImagePickerController *)picker didFinishSelectedImages:(NSArray<UIImage *> *)images selectedAssets:(NSArray<PHAsset *> *)selectedAssets {
    self.photos = selectedAssets;
    [self.collectionView reloadData];
    [picker dismissViewControllerAnimated:YES completion:nil];
}

@end
